/**
 * 功能管理
 * @constructor
 */
function User() {
}

User.init = function () {
    let vm = new Vue({
        el: "#customModule",
        data: {
            //用户信息start
            userID: "",
            userName: "",
            activity: "1",
            aliasName: "",
            phone: "",
            bankName: "",
            bankNo: "",
            bankUserName: "",
            amount: "",
            storedAmount: "",
            weight: "",
            parentName: "",
            parentID: "",
            sex: "1",
            createDateTime: "1",
            email: "1",
            userType: "",
            alipay: "",
            weixinpay: "",
            secret: "",
            secret2: "",
            //用户信息end
            UserPhoneCondition:"",
            UserNameCondition: "",
            aliasNameCondition: "",
            userTypeCondition: "-1",
            activityCondition: "-1",
            clickState: "",
            roleID: "",
            isAdd: "",
            roleList: ""
        },
        created() {
            this.roleID = $.cookie('RoleIds');
            document.getElementById("activityCondition")[0].selected = true;
            self = this;
            window.changeState = self.changeState;
            window.edit = self.edit;
            window.del = self.del;
            window.detail = self.detail;
        },
        mounted() {
            this.initBootStrapSource();
            this.initRole();
        },
        methods: {
            /**
             * 获取当前角色下，可供选择的角色
             */
            initRole() {
                let url = "/RoleManage/initRole?roleID=" + $.cookie('RoleIds');
                axios.get(url).then(data => {
                    if (data.data.code === "200") {
                        this.roleList = [];
                        for (let i = 0; i < data.data.data.length; i++) {
                            let result = data.data.data[i];
                            let param = {
                                id: result.roleID,
                                name: result.roleName
                            };
                            this.roleList.push(param);
                        }
                    }
                }).catch(e => {

                })
            },
            initBootStrapSource() {
                $('#tableList').bootstrapTable({
                    url: '/UserManage/tableSearch',
                    method: 'post',
                    toolbar: "#toolbar",
                    sidePagination: 'server',
                    dataField: "data",
                    striped: true,
                    pagination: true,
                    pageNumber: 1,
                    pageSize: 10,
                    pageList: [10, 25, 50, 100],
                    sortable: true,
                    sortName: 'createDateTime',
                    sortOrder: "desc",
                    search: false,
                    showRefresh: true,
                    showColumns: true,
                    showExport: true,
                    showToggle: true,
                    queryParamsType: 'undefined',
                    queryParams: function queryParams(params) {
                        return {
                            pageSize: params.pageSize,      //页面大小
                            pageIndex: params.pageNumber,   //页码
                            sort: params.sortName,      //排序列名
                            sortOrder: params.sortOrder, //排位命令（desc，asc）
                            userName: $('#UserNameCondition').val(),
                            phone: $('#UserPhoneCondition').val(),
                            activity: $('#activityCondition').val(),
                            roleID: $.cookie('RoleIds')
                        };
                    },
                    onLoadSuccess: function (data) {
                        //Help.alertSuccMessage("数据加载完毕");
                    },
                    onLoadError: function (status) {
                        // Help.alertErrorMessage("数据加载出错");
                    },
                    columns: [
                        {
                            title: '序号',//标题  可不加
                            align: "center",
                            width: 40,
                            sortable: true,
                            formatter: function (value, row, index) {
                                var pageSize = $('#tableList').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                                var pageNumber = $('#tableList').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                                return pageSize * (pageNumber - 1) + index + 1;//返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
                            }
                        },
                        {field: 'userID', title: '用户编号', align: 'center'},
                        {field: 'userName', title: '用户名', align: 'center', sortable: true},
                        // {field: 'aliasName', title: '商户名称', align: 'center', sortable: true},
                        {field: 'phone', title: '联系电话', align: 'center', sortable: true},

                        {field: 'parentName', title: '上级商家', align: 'center', visible: false},
                        {field: 'parentID', title: '上级编号', align: 'center', visible: false},
                        {field: 'roleID', title: '角色编号', align: 'center', visible: false},
                        {field: 'roleName', title: '角色名称', align: 'center'},
                        {
                            field: 'sex', title: '性别', align: 'center', visible: false, formatter(value, row, index) {
                                return value === 1 ? '男' : '女';
                            }
                        },

                        {field: 'createDateTime', title: '创建时间', align: 'center', sortable: true},
                        {field: 'email', title: '邮箱地址', align: 'center', visible: false},
                        {
                            field: 'userType',
                            title: '用户类型',
                            align: 'center',
                            formatter(value, row, index) {
                                if (row.userType === 0) return '管理员';
                                else if (row.userType === 1) return '商户';
                                else return '';
                            }
                        },
                        {field: 'alipay', title: '支付宝', align: 'center', visible: false},
                        {field: 'weixinpay', title: '微信', align: 'center', visible: false},
                        {
                            field: 'activity', title: '是否激活', align: 'center', sortable: true,
                            formatter: function (value, row, index) {
                                let optionHtml = "";
                                if (row.activity === 0) {
                                    optionHtml = "<span class=\"label label-danger custom\" style=\"cursor:pointer\" onclick='changeState(" + JSON.stringify(row) + ")'  title=\"未激活\" >未激活</span>";
                                } else if (row.activity === 1) {
                                    optionHtml = "<span class=\"label label-info\" style=\"cursor:pointer\" onclick='changeState(" + JSON.stringify(row) + ")' title=\"已激活\">已激活</span>";
                                }
                                return optionHtml;

                            }
                        },
                        {
                            title: '操作', align: 'center',
                            formatter: function (value, row, index) {
                                let optionHtml;
                                for (let i = 0; i < row.buttonList.length; i++) {
                                    let button = row.buttonList[i];
                                    if (button.enDesc === "Select")
                                        optionHtml = " <a class=\"btn btn-info btn-xs\" href=\"javascript:void(0)\"  onclick='detail(" + JSON.stringify(row) + ")' title=\"详细\"><i class=\"fa fa-search\"></i>详细</a>";
                                    else if (button.enDesc === "Delete")
                                        optionHtml = optionHtml + " <a class=\"btn btn-danger btn-xs\" href=\"javascript:void(0)\"  onclick='del(" + JSON.stringify(row) + ")' title=\"删除\"><i class=\"fa fa-remove\"></i>删除</a>";
                                    else if (button.enDesc === "Update")
                                        optionHtml = optionHtml + "<a class=\"btn btn-success btn-xs\"  href=\"javascript:void(0)\"  onclick='edit(" + JSON.stringify(row) + ")'  title=\"修改\" ><i class=\"fa fa-edit\"></i>修改</a>";
                                    else vm.isAdd = button.enDesc === "Insert";
                                }
                                return optionHtml;
                            }
                        }
                    ]
                });
            },
            /**
             * 查询
             */
            search() {
                vm.refresh();
            },
            /**
             * 重置
             */
            reset() {
                $('#UserNameCondition').val("");
                $('#UserPhoneCondition').val("");
                $('#activityCondition').val("-1");
                vm.UserNameCondition = "";
                vm.UserPhoneCondition = "";
                vm.activityCondition = "-1";
                vm.refresh();
            },
            /**
             * 点击改变状态
             * @param data
             */
            changeState(data) {
                let url = "/UserManage/changeState";
                let pm = {
                    activity: data.activity === 1 ? 0 : 1,
                    userID: data.userID
                };
                axios.post(url, pm).then(data => {
                    if (data.data.code === "200") {
                        Help.alertInfoMessage("", "提交成功");
                        this.refresh();
                    }
                }).catch(e => {
                    console.log(e);
                    Help.alertErrorMessage("抱歉", "发生一点小错误")
                })
            },
            /**
             * 编辑
             * @param data
             */
            edit(data) {
                vm.userID = data.userID;
                vm.userName = data.userName;
                vm.activity = data.activity;
                // vm.aliasName = data.aliasName;
                vm.phone = data.phone;
                vm.bankName = data.bankName;
                vm.bankNo = data.bankNo;
                vm.bankUserName = data.bankUserName;
                vm.amount = data.amount;
                vm.storedAmount = data.storedAmount;
                vm.weight = data.weight;
                vm.parentName = data.parentName;
                vm.parentID = data.parentID;
                vm.sex = data.sex;
                vm.createDateTime = data.createDateTime;
                vm.email = data.email;
                vm.userType = data.userType;
                vm.alipay = data.alipay;
                vm.weixinpay = data.weixinpay;
                vm.roleID = data.roleID;
                vm.clickState = "edit";
                vm.secret = data.secret;
                vm.secret2 = data.secret2;
                $('#myModalAdd').modal('show');
            },
            /**
             * 删除
             * @param data
             */
            del(data) {
                swal({
                    title: "确认是否删除",
                    text: "是否确认要删除该条记录？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "删除",
                    cancelButtonText: "取消",
                    closeOnConfirm: false
                }, function () {
                    let url = "/UserManage/del";
                    let pm = {
                        userID: data.userID
                    };
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            swal("删除成功!", "请继续操作", "success");
                            vm.refresh();
                        } else {
                            swal("删除失败!", "请重试", "error");
                        }
                    }).catch(e => {
                        console.log(e);
                        Help.alertErrorMessage("抱歉", "发生一点小错误")
                    })
                });
            },
            /**
             * 详情
             */
            detail(data) {
                vm.clickState = "view";
                vm.userID = data.userID;
                vm.userName = data.userName;
                vm.activity = data.activity;
                // vm.aliasName = data.aliasName;
                vm.phone = data.phone;
                vm.bankName = data.bankName;
                vm.bankNo = data.bankNo;
                vm.bankUserName = data.bankUserName;
                vm.amount = data.amount;
                vm.storedAmount = data.storedAmount;
                vm.weight = data.weight;
                vm.parentName = data.parentName;
                vm.parentID = data.parentID;
                vm.sex = data.sex;
                vm.createDateTime = data.createDateTime;
                vm.email = data.email;
                vm.userType = data.userType;
                vm.alipay = data.alipay;
                vm.weixinpay = data.weixinpay;
                vm.roleID = data.roleID;
                vm.secret = data.secret;
                vm.secret2 = data.secret2;
                $('#myModalAdd').modal('show');

            },
            /**
             * 新增
             */
            addRecord() {
                vm.userID = "";
                vm.userName = "";
                vm.activity = "1";
                // vm.aliasName = "";
                vm.phone = "";
                vm.bankName = "";
                vm.bankNo = "";
                vm.bankUserName = "";
                vm.amount = "";
                vm.storedAmount = "";
                vm.weight = "";
                vm.parentName = "";
                vm.parentID = "";
                vm.sex = "1";
                vm.createDateTime = "";
                vm.email = "";
                vm.userType = "0";
                vm.alipay = "";
                vm.weixinpay = "";
                vm.clickState = "add";
                vm.secret = "";
                vm.secret2 = "";
                $('#myModalAdd').modal('show');
                let url = "/UserManage/addInit";
                let pm = {
                    roleID: vm.roleID
                };
            },
            /**
             * 表单验证
             */
            validateForm() {
                //validate方法参数可选
                return $("#myform").validate({
                    rules: {
                        userName: {
                            required: true,//必填
                            minlength: 3, //最少1个字符
                            maxlength: 50,//最多50个字符
                        },
                    },
                    //错误信息提示
                    messages: {
                        userName: {
                            required: "(必填)",
                            minlength: "最少3位",
                            maxlength: "最长50位",
                        },
                    },
                }).form();
            },
            /**
             * 保存
             */
            saveRecord() {
                if(!vm.validateForm()) return false;
                if (vm.clickState === "edit") {
                    let url = "/UserManage/edit";
                    let pm = {
                        userID: vm.userID,
                        userName: vm.userName,
                        activity: vm.activity,
                        // aliasName: vm.aliasName,
                        phone: vm.phone,
                        bankName: vm.bankName,
                        bankNo: vm.bankNo,
                        bankUserName: vm.bankUserName,
                        amount: vm.amount,
                        storedAmount: vm.storedAmount,
                        weight: vm.weight,
                        parentName: vm.parentName,
                        parentID: vm.parentID,
                        sex: vm.sex,
                        createDateTime: vm.createDateTime,
                        email: vm.email,
                        userType: vm.userType,
                        alipay: vm.alipay,
                        weixinpay: vm.weixinpay,
                        roleID: this.roleID,
                        secret: vm.secret,
                        secret2: vm.secret2,
                    };
                    axios.post(url, pm).then(data => {
                        if (data.data.code === "200") {
                            Help.alertInfoMessage("", "提交成功");
                            $('#tableList').bootstrapTable(('refresh'));
                            this.refresh();
                        }
                    }).catch(e => {
                        console.log(e);
                        Help.alertErrorMessage("抱歉", "发生一点小错误")
                    }).finally(() => {
                        $('#myModalAdd').modal('hide')
                    })
                } else if (vm.clickState === "add") {
                    let url = "/UserManage/add";
                    let pm = {
                        userID: vm.userID,
                        userName: vm.userName,
                        activity: vm.activity,
                        // aliasName: vm.aliasName,
                        phone: vm.phone,
                        bankName: vm.bankName,
                        bankNo: vm.bankNo,
                        bankUserName: vm.bankUserName,
                        amount: vm.amount,
                        storedAmount: vm.storedAmount,
                        weight: vm.weight,
                        parentName: $.cookie('LoginName'),
                        parentID: $.cookie('UserID'),
                        sex: vm.sex,
                        createDateTime: vm.createDateTime,
                        email: vm.email,
                        userType: vm.userType,
                        alipay: vm.alipay,
                        weixinpay: vm.weixinpay,
                        secret: vm.secret,
                        secret2: vm.secret2,
                        roleID: this.roleID,
                        currentRoleID: $.cookie('RoleIds'),
                        // menus: menus
                    };
                    axios.post(url, pm).then(data => {
                        $('#tableList').bootstrapTable(('refresh'));
                        if (data.data.code === "200") {
                            $('#myModalAdd').modal('hide')
                            swal("创建成功!", "用户名：" + vm.userName + ",初始密码：123456", "success");
                            // Help.alertWarnMessage("创建成功", "用户名：" + vm.userName + ",初始密码：123456");
                            // Help.alertInfoMessage("提示", "如需修改，请至个人中心修改密码");
                            this.refresh();
                        }else if (data.data.code === "500"){
                            swal("操作失败，该用户已存在", "请重试", "error");
                        }
                    }).catch(e => {
                        console.log(e);
                    });
                }
            },
            refresh() {
                // $('#tableList').bootstrapTable(('refresh'));
                $("#tableList").bootstrapTable("refreshOptions",{pageNumber:1});
            }
        }
    });
};

